package com.bigdata.mapreduce.topn;

import org.apache.hadoop.io.WritableComparator;

public class TSortComparator extends WritableComparator {


    public TSortComparator() {
        super(Tkey.class, true);
    }

    /**
     * 比较2个object对象，通过返回值确定2个对象的大小，从而支持排序
     * @param a the first object to be compared.
     * @param b the second object to be compared.
     * @return
     */
    @Override
    public int compare(Object a, Object b) {
        Tkey k1 = (Tkey) a;
        Tkey k2 = (Tkey) b;
        // 按照年月正序排列，如果年月相同、按照温度倒序
        int cYear = Integer.compare(k1.getYear(), k2.getYear());
        if(cYear == 0) {
            int cMonth = Integer.compare(k1.getMonth(), k2.getMonth());
            if(cMonth == 0) {
                // 年月都相同，按照温度倒序
                return -Integer.compare(k1.getTemp(), k2.getTemp());
            }
            // 年份相同，按照月份正序排列
            return cMonth;
        }
        // 按照年份正序
        return cYear;
    }
}
